package com.alexgaoyh.MutiModule.web.intercepter;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.MutiModule.common.utils.CookieUtilss;
import com.MutiModule.common.utils.DesUtilss;
import com.MutiModule.common.utils.UUIDUtil;
import com.alexgaoyh.MutiModule.web.intercepter.token.AvoidDuplicateSubmission;

public class AvoidDuplicateSubmissionInterceptor extends
		HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();

		AvoidDuplicateSubmission annotation = method
				.getAnnotation(AvoidDuplicateSubmission.class);
		if (annotation != null) {
			boolean needSave = annotation.needSaveToken();
			if (needSave) {
				String uuid = UUIDUtil.gen();
				CookieUtilss.add(response, "token", uuid, 60*60, "/");
				request.setAttribute("token", uuid);
			}

			boolean needRemove = annotation.needRemoveToken();
			if (needRemove) {
				if (isRepeatSubmit(request)) {
					System.out.println("please don't repeat submit ,url:"
							+ request.getServletPath() + "]");
					return false;
				}
				CookieUtilss.remove(request, response, "token", "/");
			}
		}
		return true;
	}

	private boolean isRepeatSubmit(HttpServletRequest request) {
		String serverToken = CookieUtilss.get(request, "token");
		if (serverToken == null) {
			return true;
		}
		String clinetToken = request.getParameter("token");
		if (clinetToken == null) {
			return true;
		}
		if (!serverToken.equals(clinetToken)) {
			return true;
		}
		return false;
	}

}